package com.aabbc.database.bean;

import com.aabbc.database.config.MultiDataSourceRegister;
import com.aabbc.database.enums.DBTypeEnum;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * DBContextHolder
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-04-02 10:59
 * @blame Team
 */
public class MultiDBContextHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    private static final AtomicInteger counter = new AtomicInteger(0);

    public static String get() {
        return contextHolder.get();
    }

    public static void master() {
        String dataSourceName = MultiDataSourceRegister.DATASOURCE_NAME_LIST.get(0);
        contextHolder.set(dataSourceName);
        System.out.println("切换数据源：" + dataSourceName);
    }

    public static void slave() {
        int total = MultiDataSourceRegister.DATASOURCE_NAME_LIST.size();
        if(total == 1){
            master();
            return;
        }
        //  轮询
        int index = (counter.getAndIncrement() % (total - 1)) + 1;
        if (counter.get() > 99999) {
            counter.set(0);
        }
        System.out.println("index: " + index);
        String dataSourceName = MultiDataSourceRegister.DATASOURCE_NAME_LIST.get(index);
        contextHolder.set(dataSourceName);
        System.out.println("切换数据源：" + dataSourceName);
    }

}
